
package httpd

import (
	"code.google.com/p/cloud9lib/trend"
	"code.google.com/p/gorilla/mux"
	"net/http"
	"encoding/json"
	"strconv"
	"log"
)

var models = make(map[string]*trend.Model)

func AddModel(name string) *trend.Model {

	models[name] = trend.NewModel()

	return models[name]
}

func topHandler(w http.ResponseWriter, req *http.Request) {

	model, ok := models[mux.Vars(req)["model"]]

	if !ok {
		log.Print("model not found")
		w.WriteHeader(404)
		return
	}

	nstr := req.FormValue("n")

	if nstr == "" {
		log.Print("missing parameter n")
		w.WriteHeader(400)
		return
	}

	n, _ := strconv.Atoi(nstr)

	order := model.Rank.Top(n)

	text, err := json.Marshal(order)

	if err != nil {
		log.Print(err)
		w.WriteHeader(500)
		return
	}

	w.Write(text)
}

func ignoreHandler(w http.ResponseWriter, req *http.Request) {

	model, ok := models[mux.Vars(req)["model"]]

	if !ok {
		log.Print("model not found")
		w.WriteHeader(404)
		return
	}


	text := req.FormValue("text")

	if text == "" {
		log.Print("no text")
		return
	}

	log.Print("ignored text:", text)

	model.Ignore.Add(text)
}

func addHandler(w http.ResponseWriter, req *http.Request) {

	model, ok := models[mux.Vars(req)["model"]]

	if !ok {
		log.Print("model not found")
		w.WriteHeader(404)
		return
	}


	text := req.FormValue("text")

	if text == "" {
		log.Print("no text")
		return
	}

	log.Print("added text:", text)

	model.Add(text)
}

func feedHandler(w http.ResponseWriter, req *http.Request) {

	model, ok := models[mux.Vars(req)["model"]]

	if !ok {
		log.Print("model not found")
		w.WriteHeader(404)
		return
	}

	text := mux.Vars(req)["text"]
	sincestr := req.FormValue("since")

	if sincestr == "" {
		sincestr = "0"
	}

	since, _ := strconv.Atoi(sincestr)

	blocking := req.FormValue("block") == "true"

	ch := make(chan trend.Occurence)

	go model.Since(text, since, ch)

	for 

	buf, err := json.Marshal(results)

	if err != nil {
		log.Print(err)
		w.WriteHeader(500)
		return
	}

	w.Write(buf)
}


func init () {

	r := mux.NewRouter()

	get := r.Methods("GET").Subrouter()
	post := r.Methods("POST").Subrouter()

//	get.HandleFunc("/", listHandler)
	get.HandleFunc("/{model}/top.json", topHandler)
	get.HandleFunc("/{model}/feed/{text}.json", feedHandler)
	post.HandleFunc("/{model}/", addHandler)
	post.HandleFunc("/{model}/ignore/", ignoreHandler)

	http.Handle("/", r)
}
